import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';

class ImagePickerWidget extends StatefulWidget {
  final Function(List<File>) onImagesSelected;
  final String? label;

  const ImagePickerWidget({
    super.key,
    required this.onImagesSelected,
    this.label = '上传图片',
  });

  @override
  ImagePickerWidgetState createState() => ImagePickerWidgetState();
}

class ImagePickerWidgetState extends State<ImagePickerWidget> {
  final List<File> _selectedImages = [];
  final ImagePicker _picker = ImagePicker();
  final FocusNode _focusNode = FocusNode(); // 定义 FocusNode
  bool _isFocused = false; // 跟踪焦点状态

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {
        _isFocused = _focusNode.hasFocus; // 更新焦点状态
      });
    });
  }

  @override
  void dispose() {
    _focusNode.dispose(); // 清理 FocusNode
    super.dispose();
  }

  Future<void> _pickImage(ImageSource source) async {
    if (source == ImageSource.gallery) {
      final List<XFile> pickedFiles = await _picker.pickMultiImage(
        imageQuality: 100,
      );
      if (pickedFiles.isNotEmpty) {
        for (var pickedFile in pickedFiles) {
          await _processImage(File(pickedFile.path));
        }
      }
    } else {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 100,
      );
      if (pickedFile != null) {
        await _processImage(File(pickedFile.path));
      }
    }
  }

  Future<void> _processImage(File imageFile) async {
    final CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: imageFile.path,
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: '裁剪图片',
          toolbarColor: Colors.blue,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.original,
          lockAspectRatio: false,
          aspectRatioPresets: [
            CropAspectRatioPreset.square,
            CropAspectRatioPreset.ratio3x2,
            CropAspectRatioPreset.original,
            CropAspectRatioPreset.ratio4x3,
            CropAspectRatioPreset.ratio16x9,
          ],
        ),
        IOSUiSettings(
          title: '裁剪图片',
          aspectRatioPresets: [
            CropAspectRatioPreset.square,
            CropAspectRatioPreset.ratio3x2,
            CropAspectRatioPreset.original,
            CropAspectRatioPreset.ratio4x3,
            CropAspectRatioPreset.ratio16x9,
          ],
        ),
      ],
    );

    if (croppedFile != null) {
      final File compressedFile = await _compressImage(File(croppedFile.path));
      setState(() {
        _selectedImages.add(compressedFile);
      });
      widget.onImagesSelected(_selectedImages);
    }
  }

  Future<File> _compressImage(File file) async {
    final String targetPath =
        '${file.path}_compressed_${DateTime.now().millisecondsSinceEpoch}.jpg';
    final XFile? compressedXFile =
        await FlutterImageCompress.compressAndGetFile(
          file.absolute.path,
          targetPath,
          quality: 85,
          minWidth: 800,
          minHeight: 800,
        );

    return compressedXFile != null ? File(compressedXFile.path) : file;
  }

  void _removeImage(int index) {
    setState(() {
      _selectedImages.removeAt(index);
    });
    widget.onImagesSelected(_selectedImages);
  }

  @override
  @override
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        _focusNode.requestFocus();
      },
      child: SizedBox(
        height: 120,
        child: Container(
          decoration: BoxDecoration(
            border: Border.all(
              color:
                  _isFocused
                      ? Theme.of(context).colorScheme.primary
                      : Theme.of(context).colorScheme.outline,
              width: _isFocused ? 2 : 1,
            ),
            borderRadius: BorderRadius.circular(4),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(
                        Icons.image,
                        color: Theme.of(
                          context,
                        ).colorScheme.onSurface.withAlpha((0.6 * 255).round()),
                      ),
                      const SizedBox(width: 8),
                      const Spacer(),
                      IconButton(
                        icon: const Icon(Icons.add),
                        color: Theme.of(context).colorScheme.primary,
                        onPressed: () {
                          _focusNode.requestFocus();
                          showModalBottomSheet(
                            context: context,
                            builder:
                                (context) => SafeArea(
                                  child: ListView(
                                    shrinkWrap: true,
                                    children: [
                                      ListTile(
                                        leading: Icon(
                                          Icons.photo,
                                          color:
                                              Theme.of(
                                                context,
                                              ).colorScheme.primary,
                                        ),
                                        title: Text(
                                          '从相册选择',
                                          style:
                                              Theme.of(
                                                context,
                                              ).textTheme.bodyLarge,
                                        ),
                                        onTap: () {
                                          _pickImage(ImageSource.gallery);
                                          Navigator.pop(context);
                                        },
                                      ),
                                      const Divider(height: 1),
                                      ListTile(
                                        leading: Icon(
                                          Icons.camera_alt,
                                          color:
                                              Theme.of(
                                                context,
                                              ).colorScheme.primary,
                                        ),
                                        title: Text(
                                          '拍照',
                                          style:
                                              Theme.of(
                                                context,
                                              ).textTheme.bodyLarge,
                                        ),
                                        onTap: () {
                                          _pickImage(ImageSource.camera);
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                          );
                        },
                      ),
                    ],
                  ),
                  Expanded(
                    child:
                        _selectedImages.isEmpty
                            ? const SizedBox.shrink()
                            : SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              child: Row(
                                children:
                                    _selectedImages.asMap().entries.map((
                                      entry,
                                    ) {
                                      final int index = entry.key;
                                      final File image = entry.value;
                                      return Padding(
                                        padding: const EdgeInsets.only(
                                          right: 12,
                                        ),
                                        child: Stack(
                                          children: [
                                            Card(
                                              elevation: 2,
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(8),
                                                side: BorderSide(
                                                  color:
                                                      Theme.of(
                                                        context,
                                                      ).colorScheme.outline,
                                                  width: 1,
                                                ),
                                              ),
                                              child: SizedBox(
                                                width: 88,
                                                height: 88,
                                                child: ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(8),
                                                  child: Image.file(
                                                    image,
                                                    fit: BoxFit.cover,
                                                    width: 88,
                                                    height: 88,
                                                  ),
                                                ),
                                              ),
                                            ),
                                            Positioned(
                                              top: 0,
                                              right: 0,
                                              child: IconButton(
                                                onPressed:
                                                    () => _removeImage(index),
                                                icon: const Icon(Icons.close),
                                                iconSize: 16,
                                                color:
                                                    Theme.of(
                                                      context,
                                                    ).colorScheme.onError,
                                                style: IconButton.styleFrom(
                                                  backgroundColor:
                                                      Theme.of(
                                                        context,
                                                      ).colorScheme.error,
                                                  shape: const CircleBorder(),
                                                  padding: const EdgeInsets.all(
                                                    4,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      );
                                    }).toList(),
                              ),
                            ),
                  ),
                ],
              ),
              Positioned(
                left: 40,
                top: _isFocused ? 0 : 24,
                child: AnimatedContainer(
                  duration: const Duration(milliseconds: 200),
                  child: Text(
                    widget.label ?? '上传图片',
                    style: TextStyle(
                      fontSize: _isFocused ? 12 : 16,
                      color:
                          _isFocused
                              ? Theme.of(context).colorScheme.primary
                              : Theme.of(context).colorScheme.onSurface
                                  .withAlpha((0.6 * 255).round()),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
